﻿using UnityEngine;
using Musi.Core.CSV;
using System.Collections.Generic;

namespace Musi
{
    [System.Serializable]
    public class ChartNote: ICSVParseList<ChartNote>
    {
        public ChartTime startTime;
        public ChartTime endTime;
        public Vector2Int[] notesPos;

        public ChartNote()
        {
            startTime = new ChartTime();
            endTime = new ChartTime();
            notesPos = null;
        }

        public ChartNote(ChartTime start, ChartTime end, Vector2Int[] notesPos)
        {
            this.startTime = start;
            this.endTime = end;
            this.notesPos = notesPos;
        }

        public ChartNote CSVParseList(string[] sources)
        {
            if (startTime.CSVParse(sources[0]) == null)
                return null;

            if (endTime.CSVParse(sources[1]) == null)
                return null;

            List<(int, int)> posList = new List<(int, int)>();
            for (int i = 2; i < sources.Length; i++)
            {
                var result = CSVParser.ParseTupleInt(sources[i]);
                if(result.IsOk())
                    posList.Add(result.Unwarp());
            }

            (int, int)[] pos = posList.ToArray();
            notesPos = new Vector2Int[pos.Length];
            for(int posIndex = 0;posIndex < pos.Length;posIndex ++)
            {
                notesPos[posIndex].x = pos[posIndex].Item1;
                notesPos[posIndex].y = pos[posIndex].Item2;
            }

            return this;
        }

        public static List<ChartNote> NotesParse(CSVParser parser)
        {
            int start = parser.Find("[=[Notes]=]").Item1;
            int end = parser.Find("[=[NotesEnd]=]").Item1;

            List<ChartNote> notes = new List<ChartNote>();

            for (int ind = start + 1;ind != end;ind ++)
            {
                notes.Add(new ChartNote().CSVParseList(parser[ind].ToArray()));
            }

            return notes;
        }
    }
}
